package com.dsunsoft.rtu.rabbitmq;

import com.dsunsoft.rtu.common.constant.CommonConstants;
import com.dsunsoft.rtu.service.DataService;
import com.dsunsoft.rtu.service.RtuLogService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 消息队列监听
 */
@Slf4j
@Component
public class TaskListener2 {

    @Autowired
    private DataService dataService;
    @Autowired
    private RtuLogService rtuLogService;

    @RabbitListener(queues = CommonConstants.TASK_QUEUE)
    public void process(String content, Channel channel, Message message) throws IOException {
        String errMsg = null;
        boolean isSuccess = true;
        long startMillis = System.currentTimeMillis();
        try {
            // 处理
            dataService.save(content);

        } catch (Exception e) {
            isSuccess = false;
            errMsg = e.getMessage();
            log.error("消息队列处理出错_2: ", e);
        } finally {
            long totalMillis = System.currentTimeMillis() - startMillis;
            log.info("消息队列处理耗时_2: {} ms.", totalMillis);
            // ack, 向服务器发送消息确认，服务器再删除该消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            if (!isSuccess) {
                // 异常存库
                rtuLogService.save(content, errMsg);
            }
        }
    }
}
